package com.nchu.learn.netty.coder;

import com.nchu.learn.netty.enums.MessageTypeEnum;
import com.nchu.learn.netty.model.Constants;
import com.nchu.learn.netty.model.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 解码器
 * 将byte报文数据转Message对象
 *
 * @author fujianjian
 * @project self-learning
 * @date 2020/1/16 10:36
 */
public class MessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        Message message = new Message();
        message.setMagicNumber(byteBuf.readInt());
        message.setMainVersion(byteBuf.readByte());
        message.setSubVersion(byteBuf.readByte());
        message.setModifyVersion(byteBuf.readByte());

        CharSequence sessionId = byteBuf.readCharSequence(Constants.SESSION_ID_LENGTH, Charset.defaultCharset());
        message.setSessionId((String) sessionId);

        message.setMessageType(MessageTypeEnum.get(byteBuf.readByte()));
        short attachmentSize = byteBuf.readShort();
        for (int i = 0; i < attachmentSize; i++) {
            int keyLen = byteBuf.readInt();
            CharSequence key = byteBuf.readCharSequence(keyLen, Charset.defaultCharset());
            int valLen = byteBuf.readInt();
            CharSequence val = byteBuf.readCharSequence(valLen, Charset.defaultCharset());
            message.addAttachment((String) key, (String) val);
        }

        int bodyLen = byteBuf.readInt();
        CharSequence body = byteBuf.readCharSequence(bodyLen, Charset.defaultCharset());
        message.setBody(body.toString());

        list.add(message);
    }
}
